var ProjectUpdate = function () {
	var handleValidation = function() {
		var fileList = new Array();
			$('#type').change(function(){ 
				var selected = $(this).children('option:selected').val(); 
				var guaranteeTypeDiv = $('#guaranteeTypeDiv');
				var guaranteeAssessDiv = $('#guaranteeAssessDiv');
				if (2 == selected){
					guaranteeTypeDiv.css('display','none');
					guaranteeAssessDiv.css('display','none');
				} else {
					guaranteeTypeDiv.css('display','block');
					guaranteeAssessDiv.css('display','block');
				}
			}) 
			$('#guaranteeType').change(function(){ 
				var selected = $(this).children('option:selected').val(); 
				var obj = $('#guaranteeLabel');
				var guaranteeAssessDiv = $('#guaranteeAssessDiv');
				var guaranteeAssessLabel = $('#guaranteeAssessLabel');
				switch (selected) {
                case ("1"):
                		obj.html('<font color="red">*&nbsp;&nbsp;</font>保证人:');
						guaranteeAssessDiv.css('display','none');
                    break;
                case ("2"):
	                	obj.html('<font color="red">*&nbsp;&nbsp;</font>抵押人:');
                		guaranteeAssessDiv.css('display','block');
                		guaranteeAssessLabel.html('<font color="red">*&nbsp;&nbsp;</font>抵押物状况/评估:')
                    break;
                case ("3"):
	                	obj.html('<font color="red">*&nbsp;&nbsp;</font>质押人:');
                		guaranteeAssessDiv.css('display','block');
                		guaranteeAssessLabel.html('<font color="red">*&nbsp;&nbsp;</font>质押物状况/评估:')
                    break;
                case ("4"):
                		obj.html('<font color="red">*&nbsp;&nbsp;</font>留置人:');
		                guaranteeAssessDiv.css('display','block');
		        		guaranteeAssessLabel.html('<font color="red">*&nbsp;&nbsp;</font>备注:')
                      break;
                case ("5"):
                		obj.html('<font color="red">*&nbsp;&nbsp;</font>缴款人:');
		                guaranteeAssessDiv.css('display','block');
		        		guaranteeAssessLabel.html('<font color="red">*&nbsp;&nbsp;</font>备注:')
                      break;
                default:
				}
			}) 
            var formAdd = $('#addForm');
            jQuery.validator.addMethod("isCorrectNumber", function(value, element) {
            	var length = value.length;
            	var number = /^([1-9]\d*(.\d{2})?)$/;
            	return this.optional(element) || number.test(value);
            	}, "请输入正确的金额(正整数)");
            var projectId = $('#projectId').val();
            var validator = formAdd.validate({
                focusInvalid: true,
                rules: {
                	name: {
                        required: true,
                        remote:{
                        	url: ctx + "/project/check",
                            type: "post",
                            dataType: "json",
                            data: {type : 3,"id":projectId}
                        },
                    },
                    code:{
                    	required: true,
                    	remote:{
                        	url: ctx + "/project/check",
                            type: "post",
                            dataType: "json",
                            data: {type : 4,"id":projectId}
                        },
                    },
                    type:{
                    	required: true,
                    },
                    enterpriseId:{
                    	required: true,
                    },
                    guaranteeType:{
                    	required: true,
                    },
                    guaranteeEnterpriseId:{
                    	required: true,
                    },
                    guaranteeAssess:{
                    	required: true,
                    },
                    amount:{
                    	required: true,
                    	isCorrectNumber:true,
                    },
                    lawEmployeeId:{
                    	required: true,
                    },
                    summary:{
                    	required: true
                    }
                },
                messages:{
                	name: {
                        required: "项目名称不能为空",
                        remote:"项目名称已被使用",
                    },
                    code: {
                        required: "项目编号不能为空",
                        remote:"项目编号已被使用",
                    },
                	guaranteeAssess:{
	                    required:"抵押物状况/评估不能为空"
	                  },
                },
                success: function (label, element) {
                    var icon = $(element).parent('.input-icon').children('i');
                    $(element).closest('.form-group').removeClass('has-error').addClass('has-success'); // set success class to the control group
                    icon.removeClass("fa-warning").addClass("fa-check");
                },

                submitHandler: function (form) {
                	$('#submit_manager').attr('disabled',true);
                	validateContent();
                	validateContent1();
                    var content = $($('.note-editable')[0]).code();
                    if("" == content.trim() || "<p><br></p>" == content.trim()){
                    	return;
                    }
                    var plan = $($('.note-editable')[1]).code();
                    if("" == plan.trim() || "<p><br></p>" == plan.trim()){
                    	return;
                    }
                    var fd = new FormData();
                    for(var i=0;i<fileList.length;i++){
                    	fd.append("fileList", fileList[i]);
                    }
                    fd.append("id",$('#projectId').val());
                    fd.append("amount",$('input[name="amount"]').val());
                    fd.append("lawEmployeeId",$('select[name="lawEmployeeId"]').val());
                    fd.append("guaranteeAssess",$('textarea[name="guaranteeAssess"]').val().trim());
                    fd.append("guaranteeType",$('select[name="guaranteeType"]').val());
                    fd.append("guaranteeEnterpriseId",$('select[name="guaranteeEnterpriseId"]').val());
                    fd.append("type",$('select[name="type"]').val());
                    fd.append("enterpriseId",$('select[name="enterpriseId"]').val());
                    fd.append("name",$('input[name="name"]').val());
                    fd.append("code",$('input[name="code"]').val());
                    fd.append("introduction",content);
                    fd.append("plan",plan);
                    
                    var xhr = new XMLHttpRequest();
                    xhr.addEventListener("load", uploadComplete, false);
                    xhr.addEventListener("error", uploadFailed, false);
                    xhr.open("POST",ctx + "/project/update");
                    xhr.send(fd);
                    
                    function uploadComplete(evt) {
                        /* This event is raised when the server send back a response */
                        var msg = JSON.parse(evt.target.responseText);
                        if(0 == msg.code){
                    		bootbox.alert(msg.message);
                    		$('#submit_manager').removeAttr("disabled");
                    		return;
                    	}
                    	bootbox.alert({  
                            buttons: {  
                               ok: {  
                                    label: '确认',  
                                    className: 'btn-primary'  
                                }  
                            },  
                            message: '修改项目成功！',  
                            callback: function() {  
                            	$('#submit_manager').removeAttr("disabled");
                            	//重定向到未入库项目页面
                            	window.location.href = ctx +"/project/nonInStoreList";
                            },  
                            title: "提示信息",  
                        }); 
                    	$('#submit_manager').removeAttr("disabled");
                      }

                      function uploadFailed(evt) {
                        alert("There was an error attempting to upload the file.");
                      }
                    
//                    var json = $('form#addForm').serializeObject();
//    				json.introduction=content;
//    				json.plan = plan;
//    				json.fileList = fileList;
//                    $.ajax({
//                    	type:"post",
//                        url: ctx + "/project/doAdd",
//                        data:json,
//                        success: function(msg){
//                        	if(msg.code == 1){
//                        		bootbox.alert("新增项目成功");
//                        	}
//                        	$('#btn_submit').attr('disabled',false);
////                        	window.location.reload()
//                        },
//                        error: function (msg) {
//                        	bootbox.alert("服务器偷了个小懒,新增项目失败了！");
//                        }
//                    });
                }
            });
            $('button[name="addEnterprise"]').click(function(){
            	window.location.href=ctx+'/enterprise/add';
            });
            
            var validateContent = function(){
            	var c = $($('.note-editable')[0]).html().toString();
            	if("" == c.trim() || "<p><br></p>" == c.trim()){
            		$($('.note-editor')[0]).removeClass("content-control has-success").addClass("content-control error");
	            	if($('#content-label').hasClass("content-success")){
	            		$('#content-label').removeClass("content-success");
	            	}
	            	$("#contents-error").html('内容不能为空'); 
	            	$("#contents-error").css('display','inline'); 
	            }else{
	            	$($('.note-editor')[0]).removeClass("content-control error").addClass("content-control has-success");
	            	$('#content-label').addClass("content-success");
	            	$("#contents-error").css('display','none'); 
	            }
            };
            var validateContent1 = function(){
            	var c = $($('.note-editable')[1]).html().toString();
            	if("" == c.trim() || "<p><br></p>" == c.trim()){
	            	$($('.note-editor')[1]).removeClass("content-control has-success").addClass("content-control error");
	            	if($('#content-label1').hasClass("content-success")){
	            		$('#content-label1').removeClass("content-success");
	            	}
	            	$("#contents-error1").html('内容不能为空'); 
	            	$("#contents-error1").css('display','inline'); 
	            }else{
	            	$($('.note-editor')[1]).removeClass("content-control error").addClass("content-control has-success");
	            	$('#content-label1').addClass("content-success");
	            	$("#contents-error1").css('display','none'); 
	            }
            };
            $($('.summernote')[0]).summernote({
            	height: 500, 
            	toolbar: [  
            	          ['style', ['style']],
            	          ['style', ['bold', 'italic', 'underline', 'clear']],  
            	          ['fontsize', ['fontsize']],  
            	          ['fontname',['fontname']],
            	          ['color', ['color']],  
            	          ['para', ['ul', 'ol', 'paragraph']],  
            	          ['height', ['height']],  
            	          ['table',['table']],
            	          ['insert', ['picture','link']] ,
            	          ['help',['help']]
            	        ], 
            	onImageUpload: function(files, editor, $editable) {
                     sendFile(files,editor,$editable);
                    },
                onblur: function(e) {
                	validateContent();
                },
                onfocus:function(e){
                	validateContent();
                },
                onChange: function(contents, $editable) {
                	validateContent();
                },
                bFullscreen:false,
                
            });
            $($('.summernote')[1]).summernote({
            	height: 500, 
            	toolbar: [  
            	          ['style', ['style']],
            	          ['style', ['bold', 'italic', 'underline', 'clear']],  
            	          ['fontsize', ['fontsize']],  
            	          ['fontname',['fontname']],
            	          ['color', ['color']],  
            	          ['para', ['ul', 'ol', 'paragraph']],  
            	          ['height', ['height']],  
            	          ['table',['table']],
            	          ['insert', ['picture','link']] ,
            	          ['help',['help']]
            	        ], 
            	onImageUpload: function(files, editor, $editable) {
                     sendFile(files,editor,$editable);
                    },
                onblur: function(e) {
                	validateContent1();
                },
                onfocus:function(e){
                	validateContent1();
                },
                onChange: function(contents, $editable) {
                	validateContent1();
                },
                bFullscreen:false,
                
            });
            function sendFile(file, editor, $editable) {
            	for(var i = 0;i < file.length;i++){
            		data = new FormData();
                    data.append("file", file[i]);
                    url = ctx+"/project/imgUploads";
                    $.ajax({
                        data: data,
                        type: "POST",
                        url: url,
                        cache: false,
                        contentType: false,
                        processData: false,
                        success: function (msg) {
                        	if(1 == msg.code){
//                        		editor.insertImage($editable, imagePrefix+encodeURIComponent(msg.data));
                        		editor.insertImage($editable, imagePrefix+msg.data);
                        	}
                        	else{
                        		bootbox.alert(msg.message);
                        	}
//                        	$('.summernote').summernote('editor.insertImage', "product/downloadFile?filePath="+msg.data); 
                        }
                 	});
            	}
                
       		};
    }

    return {
        init: function () {
            handleValidation();
        }
    };
}();

//新增企业附件
function uploadRelatedFile(){
		if(!$("#relatedFile").val()){
			bootbox.alert("请先添加文件！");
			return;
		}
		 $.ajaxFileUpload({
              url: ctx + '/projectAttachment/uploadRelatedFile',
              type: 'post',
              secureuri: false,
              fileElementId: 'relatedFile',
              dataType: 'json',
              data: {'projectId': $("input[name=id]").val(),'type':1},
              success: function(data, status){
              	if (data.code == 1) {
              		bootbox.dialog({
      					message : "上传成功！ ",
      					title : "温馨提示：",
      					buttons : {
      						main : {
      							label : "确定",
      							className : "btn btn-outline btn-primary",
      							callback : function() {
      								getRelatedFile();
      							}
      						}
      					}
      				});
              		
              	} else {
              		bootbox.alert(data.message);
              	}
              },
              error: function(msg, status, e){
              	bootbox.alert("上传失败！");
              }
          });
		 } 
  
  
  function deleteThisFile(obj){
      bootbox.confirm("您确定要删除这个文件?", function(result) {
          if (result) {
          	var nRow = $(obj).parents('div')[0];
            var id = nRow.id;
              $.ajax({
              	type:"get",
                  url: ctx + "/projectAttachment/delete/"+id,
                  dataType:"json",
                  success: function(msg){
                  	if (msg.code == 1) {
                  		getRelatedFile();
                  		bootbox.alert("删除文件成功！");
                  	} else {
                  		bootbox.alert("删除文件失败！");
                  	}
                  },
                  error: function (msg) {
                  	bootbox.alert(msg.message);
                  }
              });
          }
      });
  }
  
  function getRelatedFile(){
  	$.ajax({
      	type:"get",
          url: ctx + "/projectAttachment/query/"+$("#projectId").val(),
          dataType:"json",
          success: function(data){
          	if (data.code == 1) {
          		var objs = data.data.projectAttachmentList;
              	var html = "";
              	var closeBttn = ' &nbsp;<button  type="button"  class="btn btn-outline btn-primary btn-xs" onclick="deleteThisFile(this)">删除</button>&nbsp;';
              	for(var i=0;i<objs.length;i++){
              		var id = objs[i].id;
              		var fileName = objs[i].contractName;
              		var renameBttn = '<button id="'+id+'" name="'+fileName+'" type="button" class="btn btn-outline btn-primary btn-xs" onclick="showRenameDialog(this)">重命名</button>';
              		html+="<div style='padding-top:2px' id='"+id+"'>"+fileName+closeBttn+renameBttn+"</div>";
              	}
              	$("#relatedFileId").html(html);
          	}
          },
          error: function (msg) {
          	bootbox.alert(msg.message);
          }
      });
  }
  var modal;
  function showRenameDialog(obj){
  	var filename = $(obj).attr('name').split(".")[0];
  	$("#o_renameFileName").val(filename);
  	$("#renameFileName").val(filename);
  	$("#renameFileName").attr('name',$(obj).attr('id'));
  	modal = $('#updateModel_relatedFile').modal('show');
  }
  
 //项目附件重命名 
 function renameFile(){
  	var o_filename = $("#o_renameFileName").val();
  	var filename = $("#renameFileName").val();
  	if(o_filename==filename){
  		bootbox.alert("请输入与原文件名不同的名字！");
  		return;
  	}
    var id = $("#renameFileName").attr('name');
	var json = "{\"id\":\""+id+"\",\"contractName\":\""+filename+"\"}";
  	$.ajax({
      	type:"post",
          url: ctx + "/projectAttachment/rename",
          contentType:"application/json; charset=UTF-8",
          data:json,
          dataType:"json",
          success: function(data){
          	if (data.code == 1) {
          		modal.modal('hide');
          		bootbox.alert("更新文件名字成功！");
          		getRelatedFile();
          	}
          },
          error: function (msg) {
          	bootbox.alert(msg.message);
          }
      });
  }